import { Table, Tag, Typography, Card, Button, Space, Modal, Form, Input, Select, InputNumber, DatePicker, message, Row, Col, Avatar, Upload, Switch, Tooltip, Popconfirm } from '@/utils/antd-imports';
import { EditOutlined, PlusOutlined, DeleteOutlined, UserOutlined, UploadOutlined, EyeOutlined, EyeInvisibleOutlined, CrownOutlined, SafetyOutlined } from '@/utils/icons';
import React, { useState, useEffect } from 'react';
import moment from 'moment';
import fileApi from '../../api/fileApi';
import userApi from '../../api/userApi';
import employeeApi from '../../api/employeeApi';

const { Title, Text } = Typography;
const { Option } = Select;

// 用户类型映射
const userTypeMap = {
  'super_admin': '总管理员',
  'admin': '管理员',
  'sub_admin': '子管理员',
  'user': '普通用户'
};

const UserManagement = () => {
  const [users, setUsers] = useState([]);
  const [employees, setEmployees] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [form] = Form.useForm();
  const [searchText, setSearchText] = useState('');
  const [selectedUserType, setSelectedUserType] = useState('');
  const [selectedStatus, setSelectedStatus] = useState('');
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });

  // 加载用户列表
  const loadUsers = async (page = 1, size = 10) => {
    try {
      setLoading(true);
      const response = await userApi.getUserList();
      if (response.code === 200) {
        const userList = response.data || [];
        setUsers(userList);
        setPagination(prev => ({
          ...prev,
          current: page,
          total: userList.length
        }));
      } else {
        message.error('加载用户列表失败');
      }
    } catch (error) {
      console.error('加载用户列表失败:', error);
      message.error('加载用户列表失败');
    } finally {
      setLoading(false);
    }
  };

  // 加载员工列表
  const loadEmployees = async () => {
    try {
      // 使用员工管理API获取在职员工列表
      const response = await employeeApi.getEmployeesByStatus(1); // 1表示在职员工
      if (response.code === 200) {
        setEmployees(response.data || []);
      } else {
        console.error('加载员工列表失败:', response.message);
      }
    } catch (error) {
      console.error('加载员工列表失败:', error);
    }
  };

  // 组件挂载时加载数据
  useEffect(() => {
    loadUsers();
    loadEmployees();
  }, []);

  // 筛选数据
  const filteredUsers = users.filter(user => {
    const matchesSearch = !searchText || 
                         (user.username && user.username.includes(searchText)) ||
                         (user.employeeName && user.employeeName.includes(searchText));
    const matchesUserType = !selectedUserType || user.userType === selectedUserType;
    const matchesStatus = !selectedStatus || user.status === selectedStatus;
    
    return matchesSearch && matchesUserType && matchesStatus;
  });

  // 处理添加/编辑用户
  const handleEdit = (user = null) => {
    setCurrentUser(user);
    if (user) {
      form.setFieldsValue({
        username: user.username,
        employeeId: user.employeeId,
        administrator: user.administrator || 0
      });
    } else {
      form.resetFields();
    }
    setModalVisible(true);
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      
      if (currentUser) {
        // 编辑用户 - 这里需要根据实际API调整
        message.info('编辑用户功能需要根据实际API实现');
      } else {
        // 创建用户
        const userData = {
          username: values.username,
          password: values.password,
          administrator: values.administrator
        };
        
        // 只有当employeeId存在时才添加该字段
        if (values.employeeId) {
          userData.employeeId = values.employeeId;
        }
        
        const response = await userApi.createUser(userData);
        if (response.code === 200) {
          message.success('用户创建成功');
          loadUsers(); // 重新加载用户列表
          setModalVisible(false);
          form.resetFields();
        } else {
          message.error(response.message || '用户创建失败');
        }
      }
    } catch (error) {
      console.error('提交表单失败:', error);
      message.error('操作失败');
    }
  };

  // 删除用户
  const handleDelete = async (user) => {
    try {
      const response = await userApi.deleteUser(user.username);
      if (response.code === 200) {
        message.success('用户删除成功');
        loadUsers(); // 重新加载用户列表
      } else {
        message.error(response.message || '用户删除失败');
      }
    } catch (error) {
      console.error('删除用户失败:', error);
      message.error('删除用户失败');
    }
  };

  // 提升用户权限为管理员
  const handlePromoteAdmin = async (user) => {
    try {
      const response = await userApi.promoteAdmin(user.username);
      if (response.code === 200) {
        message.success('用户权限提升成功');
        loadUsers(); // 重新加载用户列表
      } else {
        message.error(response.message || '权限提升失败');
      }
    } catch (error) {
      console.error('权限提升失败:', error);
      message.error('权限提升失败');
    }
  };

  // 提升用户权限为总管理员
  const handlePromoteSuper = async (user) => {
    try {
      const response = await userApi.promoteSuper(user.username);
      if (response.code === 200) {
        message.success('用户权限提升成功');
        loadUsers(); // 重新加载用户列表
      } else {
        message.error(response.message || '权限提升失败');
      }
    } catch (error) {
      console.error('权限提升失败:', error);
      message.error('权限提升失败');
    }
  };

  // 上传头像
  const handleAvatarUpload = async (file, user) => {
    try {
      const result = await fileApi.uploadEmployeeFile(user.realName, '头像', file);
      if (result.success) {
        setUsers(users.map(u => 
          u.id === user.id ? { ...u, avatar: result.data.filePath } : u
        ));
        message.success('头像上传成功');
      } else {
        message.error('头像上传失败');
      }
    } catch (error) {
      message.error('头像上传失败');
    }
    return false; // 阻止默认上传行为
  };

  // 用户表格列定义
  const userColumns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      width: 120,
      render: (text) => <Text strong>{text}</Text>
    },
    {
      title: '员工姓名',
      dataIndex: 'employeeName',
      key: 'employeeName',
      width: 120
    },
    {
      title: '员工编号',
      dataIndex: 'employeeCode',
      key: 'employeeCode',
      width: 120
    },
    {
      title: '用户类型',
      dataIndex: 'userType',
      key: 'userType',
      width: 120,
      render: (userType) => {
        const colors = {
          'super_admin': 'red',
          'admin': 'orange',
          'sub_admin': 'purple',
          'user': 'green'
        };
        return <Tag color={colors[userType]}>{userTypeMap[userType] || userType}</Tag>;
      }
    },
    {
      title: '管理员标识',
      dataIndex: 'administrator',
      key: 'administrator',
      width: 100,
      render: (administrator) => (
        <Tag color={administrator ? 'blue' : 'default'}>
          {administrator ? '是' : '否'}
        </Tag>
      )
    },
    {
      title: '员工ID',
      dataIndex: 'employeeId',
      key: 'employeeId',
      width: 100
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 150,
      render: (time) => time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : '-'
    },
    {
      title: '最后登录',
      dataIndex: 'lastLoginTime',
      key: 'lastLoginTime',
      width: 150,
      render: (time) => time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : '-'
    },
    {
      title: '操作',
      key: 'action',
      width: 300,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Button 
            type="link" 
            icon={<EditOutlined />} 
            onClick={() => handleEdit(record)}
            size="small"
          >
            编辑
          </Button>
          
          {record.userType === 'user' && (
            <Tooltip title="提升为管理员">
              <Button 
                type="link" 
                icon={<SafetyOutlined />} 
                onClick={() => handlePromoteAdmin(record)}
                size="small"
              >
                提升管理员
              </Button>
            </Tooltip>
          )}
          
          {record.userType === 'admin' && (
            <Tooltip title="提升为总管理员">
              <Button 
                type="link" 
                icon={<CrownOutlined />} 
                onClick={() => handlePromoteSuper(record)}
                size="small"
              >
                提升总管理员
              </Button>
            </Tooltip>
          )}
          
          <Popconfirm
            title="确认删除"
            description={`确定要删除用户"${record.username}"吗？`}
            onConfirm={() => handleDelete(record)}
            okText="确定"
            cancelText="取消"
          >
            <Button 
              type="link" 
              danger 
              icon={<DeleteOutlined />} 
              size="small"
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      )
    }
  ];

  return (
    <div>
      <Card
        title="用户管理"
        extra={
          <Button 
            type="primary" 
            icon={<PlusOutlined />}
            onClick={() => handleEdit()}
          >
            添加用户
          </Button>
        }
      >
        {/* 搜索和筛选 */}
        <Row gutter={16} style={{ marginBottom: 16 }}>
          <Col span={6}>
            <Input
              placeholder="搜索用户名或员工姓名"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              allowClear
            />
          </Col>
          <Col span={4}>
            <Select
              placeholder="选择用户类型"
              value={selectedUserType}
              onChange={setSelectedUserType}
              allowClear
              style={{ width: '100%' }}
            >
              <Option value="super_admin">总管理员</Option>
              <Option value="admin">管理员</Option>
              <Option value="sub_admin">子管理员</Option>
              <Option value="user">普通用户</Option>
            </Select>
          </Col>
          <Col span={4}>
            <Select
              placeholder="选择状态"
              value={selectedStatus}
              onChange={setSelectedStatus}
              allowClear
              style={{ width: '100%' }}
            >
              <Option value="active">启用</Option>
              <Option value="inactive">禁用</Option>
            </Select>
          </Col>
          <Col span={6}>
            <Space>
              <Button onClick={() => {
                setSearchText('');
                setSelectedUserType('');
                setSelectedStatus('');
              }}>
                重置筛选
              </Button>
              <Button onClick={() => loadUsers()}>
                刷新
              </Button>
            </Space>
          </Col>
        </Row>

        {/* 用户表格 */}
        <Table
          columns={userColumns}
          dataSource={filteredUsers}
          rowKey="username"
          loading={loading}
          pagination={{ 
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({ ...prev, current: page, pageSize }));
              loadUsers(page, pageSize);
            }
          }}
          scroll={{ x: 1200 }}
          bordered
          size="middle"
        />
      </Card>

      {/* 添加/编辑用户对话框 */}
      <Modal
        title={currentUser ? '编辑用户' : '添加用户'}
        open={modalVisible}
        onOk={handleSubmit}
        onCancel={() => {
          setModalVisible(false);
          form.resetFields();
        }}
        width={600}
        destroyOnClose
      >
        <Form form={form} layout="vertical">
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="用户名"
                name="username"
                rules={[{ required: true, message: '请输入用户名' }]}
              >
                <Input placeholder="请输入用户名" disabled={!!currentUser} />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="密码"
                name="password"
                rules={[{ required: !currentUser, message: '请输入密码' }]}
              >
                <Input.Password placeholder="请输入密码" />
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                label="关联员工"
                name="employeeId"
              >
                <Select 
                  placeholder="请选择员工（可选）"
                  allowClear
                  showSearch
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                    option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                  }
                >
                  {employees.map(employee => (
                    <Option key={employee.id} value={employee.id}>
                      {employee.name} ({employee.employeeCode}) - {employee.department}
                    </Option>
                  ))}
                </Select>
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                label="管理员标识"
                name="administrator"
                rules={[{ required: true, message: '请选择管理员标识' }]}
              >
                <Select placeholder="请选择管理员标识">
                  <Option value={1}>是</Option>
                  <Option value={0}>否</Option>
                </Select>
              </Form.Item>
            </Col>
          </Row>
          
          <Row gutter={16}>
            <Col span={24}>
              <Form.Item
                label="说明"
                name="description"
              >
                <Input.TextArea 
                  rows={3} 
                  placeholder="请输入用户说明信息" 
                  disabled
                />
              </Form.Item>
            </Col>
          </Row>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;
